import React, { useState } from 'react';

interface ImageWithLoadingProps {
  src: string;
  alt: string;
  className?: string;
  width?: number;
  height?: number;
  style?: React.CSSProperties;
  onLoad?: () => void;
  onError?: () => void;
}

export function ImageWithLoading({ 
  src, 
  alt, 
  className = '', 
  width, 
  height, 
  style,
  onLoad,
  onError 
}: ImageWithLoadingProps) {
  const [isLoading, setIsLoading] = useState(true);
  const [hasError, setHasError] = useState(false);

  const handleLoad = () => {
    setIsLoading(false);
    if (onLoad) onLoad();
  };

  const handleError = () => {
    setIsLoading(false);
    setHasError(true);
    if (onError) onError();
  };

  return (
    <div className={`relative overflow-hidden ${className}`} style={style}>
      {/* Loading skeleton */}
      {isLoading && (
        <div 
          className="absolute inset-0 bg-gradient-to-r from-[#061a2c] via-[#0a2540] to-[#061a2c] animate-pulse-slow"
          style={{ width, height }}
        >
          <div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/10 to-transparent animate-shimmer" />
        </div>
      )}

      {/* Error placeholder */}
      {hasError && (
        <div 
          className={`flex items-center justify-center bg-[#061a2c] text-gray-400 ${className}`}
          style={{ width, height }}
        >
          <div className="text-center">
            <div className="w-12 h-12 mx-auto mb-2 bg-[#1a3a5c] rounded-lg flex items-center justify-center">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M21 19V5C21 3.9 20.1 3 19 3H5C3.9 3 3 3.9 3 5V19C3 20.1 3.9 21 5 21H19C20.1 21 21 20.1 21 19ZM8.5 13.5L11 16.51L14.5 12L19 18H5L8.5 13.5Z" fill="currentColor"/>
              </svg>
            </div>
            <p className="text-xs">Failed to load</p>
          </div>
        </div>
      )}

      {/* Actual image */}
      <img
        src={src}
        alt={alt}
        width={width}
        height={height}
        className={`w-full h-full object-cover ${isLoading ? 'opacity-0' : 'opacity-100 animate-fade-in'} transition-opacity duration-300`}
        style={style}
        onLoad={handleLoad}
        onError={handleError}
      />
    </div>
  );
}
